package com.caigou.component;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import com.aliyuncs.utils.StringUtils;
import com.caigou.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class OSSComponent {

    private Logger logger = LoggerFactory.getLogger(OSSComponent.class);

    private String endpoint;// endpoint以杭州为例，其它region请按实际情况填写
    private String accessKeyId;// accessKey
    private String accessKeySecret;// accessKeySecret
    private String bucketName;// 命名空间
    private String rootFolder;// 上传的根文件夹
    private String ossUrl;//oss绑定域名

    @Resource
    private SnowflakeComponent snowflakeComponent;// 雪花UUID组件

    private OSSClient ossClient;// // OSS客户端

    @Value("${oss.end_point}")
    public void setEndpoint(String end_point){ endpoint = end_point; }
    @Value("${oss.access_key_id}")
    public void setAccessKeyId(String access_key_id){ accessKeyId = access_key_id; }
    @Value("${oss.access_key_secret}")
    public void setAccessKeySecret(String access_key_secret){ accessKeySecret = access_key_secret; }
    @Value("${oss.bucket_name}")
    public void setBucketName(String bucket_name){ bucketName = bucket_name; }
    @Value("${oss.root_folder}")
    public void setRootFolder(String root_folder){ rootFolder = root_folder; }
    @Value("${oss.oss_url}")
    public void setOssUrl(String oss_url){ ossUrl = oss_url; }

    // 初始化
    @PostConstruct
    public void init() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }
    // 销毁
    public void destory() {
        ossClient.shutdown();
    }

    /**
     * OSS文件上传方法
     * @param file 图片音频视频文件
     * @return
     */
    public String uploadToOSS(MultipartFile file, String fileFolder) {
        long start = System.currentTimeMillis();
        logger.info("=========start upload file========"+start);
        if (null == file) return null;
        // 获取文件名称
        String fileName = file.getOriginalFilename();
        if (null == fileName || fileName.equals("")) return null;
        String fileUrl = null;
        // 进行文件上传
        try {
            InputStream inputStream = file.getInputStream();
            fileUrl = this.uploadToOSS(inputStream, fileName, fileFolder);
            long end = System.currentTimeMillis();
            logger.info("==========end upload file=========="+end+",上传到oss花费"+(end-start)/1000+"秒");
            return fileUrl;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return fileUrl;
        }
    }

    /**
     * 上传到OSS服务器  如果同名会覆盖服务器上的
     *
     * @param inputStream 文件流
     * @param fileName 文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public String uploadToOSS(InputStream inputStream, String fileName, String fileFolder) {
        String fileUrl = null;
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(inputStream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            String fileExtension = fileName.substring(fileName.lastIndexOf("."));
            objectMetadata.setContentType(getContentType(fileExtension));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);

            //文件重命名
            String newFileName = snowflakeComponent.getInstance().nextId()+fileExtension;
            logger.info("原文件={}， 重命名={}", fileName, newFileName);
            //上传文件
            PutObjectResult putResult = ossClient.putObject(bucketName, rootFolder+fileFolder+newFileName, inputStream, objectMetadata);
            String uploadResult = putResult.getETag();
            if(!StringUtils.isEmpty(uploadResult)){
                fileUrl = ossUrl+rootFolder+fileFolder+newFileName;
                logger.info("上传文件的fileUrl={}", fileUrl);
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return fileUrl;
    }

    /**
     *
     * @param inputStream 文件流
     * @param fileName 文件名称 包括后缀名
     * @param newFileName 新文件名称 包括后缀名
     * @param fileFolder 文件夹
     * @return
     */
    public String uploadToOSS(InputStream inputStream, String fileName, String newFileName, String fileFolder) {
        String fileUrl = null;
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(inputStream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            String fileExtension = fileName.substring(fileName.lastIndexOf("."));
            objectMetadata.setContentType(getContentType(fileExtension));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);

            //上传文件
            PutObjectResult putResult = ossClient.putObject(bucketName, rootFolder+fileFolder+newFileName, inputStream, objectMetadata);
            String uploadResult = putResult.getETag();
            if(!StringUtils.isEmpty(uploadResult)){
                fileUrl = ossUrl+rootFolder+fileFolder+newFileName;
                logger.info("上传文件的fileUrl={}", fileUrl);
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return fileUrl;
    }


    public String uploadToOSSByName(MultipartFile file, String fileFolder) {
        long start = System.currentTimeMillis();
        logger.info("=========start upload file========"+start);
        if (null == file) return null;
        // 获取文件名称
        String fileName = file.getOriginalFilename();
        if (null == fileName || fileName.equals("")) return null;
        String fileUrl = null;
        // 进行文件上传
        try {
            InputStream inputStream = file.getInputStream();
            fileUrl = this.uploadToOSS(inputStream, fileName,fileName, fileFolder);
            long end = System.currentTimeMillis();
            logger.info("==========end upload file=========="+end+",上传到oss花费"+(end-start)/1000+"秒");
            return fileUrl;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return fileUrl;
        }
    }

    /**
     * 上传原尺寸图片文件及压缩图片文件到oss
     * @param originInputStream
     * @param zoomInputStream
     * @param fileName
     * @param fileFolder
     * @return
     */
    public String uploadOriginAndZoomToOSS(InputStream originInputStream, InputStream zoomInputStream, String fileName, String fileFolder) {
        String fileUrl = null;
        String fileUrl2 = null;
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        //文件重命名
        String newFileName = snowflakeComponent.getInstance().nextId()+fileExtension;
        String zoomNewFileName = "small"+newFileName;
        logger.info("原文件={}， 重命名={}", fileName, newFileName);
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(originInputStream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getContentType(fileExtension));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);

            //上传源文件
            PutObjectResult putResult = ossClient.putObject(bucketName, rootFolder+fileFolder+newFileName, originInputStream, objectMetadata);
            String uploadResult = putResult.getETag();
            if(!StringUtils.isEmpty(uploadResult)){
                fileUrl = ossUrl+rootFolder+fileFolder+newFileName;
                logger.info("上传源文件的fileUrl={}", fileUrl);
            }


            //创建上传Object的Metadata
            ObjectMetadata objectMetadata2 = new ObjectMetadata();
            objectMetadata2.setContentLength(zoomInputStream.available());
            objectMetadata2.setCacheControl("no-cache");
            objectMetadata2.setHeader("Pragma", "no-cache");
            objectMetadata2.setContentType(getContentType(fileExtension));
            objectMetadata2.setContentDisposition("inline;filename=" + "small"+fileName);

            //上传压缩文件
            PutObjectResult putResult2 = ossClient.putObject(bucketName, rootFolder+fileFolder+zoomNewFileName, zoomInputStream, objectMetadata2);
            String uploadResult2 = putResult.getETag();
            if(!StringUtils.isEmpty(uploadResult2)){
                fileUrl2 = ossUrl+rootFolder+fileFolder+zoomNewFileName;
                logger.info("上传压缩文件的fileUrl2={}", fileUrl2);
            }

        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                if (originInputStream != null) {
                    originInputStream.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return fileUrl;
    }

    /**
     *
     * @param urlString
     */
    public boolean deleteFromOSS(String urlString) {
        if (urlString == null || "".equals(urlString)) {
            return false;
        }
        try {
            URL url = new URL(urlString);
            String path = url.getPath();
            if(path.startsWith("/")){
                path = path.substring(1);
            }
            /**
             * 文件夹是否存在
             */
            if (!ossClient.doesObjectExist(bucketName, rootFolder)) {
                ossClient.putObject(bucketName, rootFolder, new ByteArrayInputStream(new byte[0]));
            }

            /**
             * 对象是否存在
             */
            if (ossClient.doesObjectExist(bucketName,path)) {
                /**
                 * 删除存在对象
                 */
                ossClient.deleteObject(bucketName, path);
                return true;
            }
        } catch (MalformedURLException e) {
            logger.error(e.getMessage(), e);
        }
        return false;

    }


    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     * @param FilenameExtension 文件后缀
     * @return String
     */
    private static String getContentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        if (FilenameExtension.equalsIgnoreCase(".mp3")) {
            return "mp3";
        }
        return null;
    }

    /**
     * 获得url链接
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 设置URL过期时间为10年  3600L*1000*24*365*10
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        return url.toString().substring(0, url.toString().lastIndexOf("?"));
    }

    public String uploadLargeToOSS(MultipartFile multipartFile, String fileFolder) {
        long start = System.currentTimeMillis();
        logger.info("=========start upload file========"+start);
        if (null == multipartFile) return null;
        // 获取文件名称
        String fileName = multipartFile.getOriginalFilename();
        if (null == fileName || fileName.equals("")) return null;
        String fileUrl = null;
        // 进行文件上传
        try {
            File file = FileUtil.multipartFileToFile(multipartFile);
            String[] resultArr = this.uploadLarge2OSS(file, fileFolder);
            long end = System.currentTimeMillis();
            if (resultArr != null) {
                String path = resultArr[1];
                // 保存路径url地址：http://zhiliaoappversion.oss-cn-beijing.aliyuncs.com/appversion/20200723/a3662009-897c-43ea-a6d8-466ab8310c6b.apk
                fileUrl = getUrl(path);
            }
            logger.info("==========end upload file=========="+end+",上传到oss花费"+(end-start)/1000+"秒, fileUrl={}", fileUrl);
            return fileUrl;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return fileUrl;
        }
    }


    /**
     * 上传图片至OSS 文件流
     *
     * @param file       上传文件（文件全路径如：D:\\image\\cake.jpg）
     * @param folder     阿里云API的文件夹名称（父文件夹）
     * @return String 返回的唯一MD5数字签名
     */
    public String[] uploadLarge2OSS(File file, String folder) {
        // 创建一个可重用固定线程数的线程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);
        String[] resultArr = new String[2];
        try {
            // 文件名
            String fileName = file.getName();
            // 文件扩展名
            String fileExtension = fileName.substring(fileName.lastIndexOf("."));
            // 最终文件名：UUID + 文件扩展名
            String newFileName = String.valueOf(UUID.randomUUID());
            fileName = newFileName + fileExtension;
            // 上传路径 如：appversion/20200723/a3662009-897c-43ea-a6d8-466ab8310c6b.apk
            // objectName表示上传文件到OSS时需要指定包含文件后缀在内的完整路径，例如abc/efg/123.jpg
            String objectName = folder + fileName;
            log.info("上传到路径：" + objectName);
            // 文件大小
            long fileSize = file.length();
            // 创建上传Object的Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            // 指定该Object被下载时的网页的缓存行为
            metadata.setCacheControl("no-cache");
            // 指定该Object下设置Header
            metadata.setHeader("Pragma", "no-cache");
            // 指定该Object被下载时的内容编码格式
            metadata.setContentEncoding("utf-8");
            // 文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
            // 如果没有扩展名则填默认值application/octet-stream
            metadata.setContentType(getContentType(fileExtension));
            // 指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
            metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
            // 创建InitiateMultipartUploadRequest对象
            InitiateMultipartUploadRequest request = new InitiateMultipartUploadRequest(bucketName, objectName, metadata);
            // 初始化分片
            InitiateMultipartUploadResult upresult = ossClient.initiateMultipartUpload(request);
            // 返回uploadId，它是分片上传事件的唯一标识，您可以根据这个uploadId发起相关的操作，如取消分片上传、查询分片上传等
            String uploadId = upresult.getUploadId();
            // partETags是PartETag的集合。PartETag由分片的ETag和分片号组成
            List<PartETag> partETags = Collections.synchronizedList(new ArrayList<>());
            // 计算文件有多少个分片
            final long partSize = 1 * 1024 * 1024L; // 1MB
            long fileLength = file.length();
            int partCount = (int) (fileLength / partSize);
            if (fileLength % partSize != 0) {
                partCount++;
            }
            if (partCount > 10000) {
                throw new RuntimeException("分片总块数不能超过10000");
            } else {
                log.info("分片总块数：" + partCount);
            }
            // 遍历分片上传
            for (int i = 0; i < partCount; i++) {
                long startPos = i * partSize;
                long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize;
                int partNumber = i + 1;
                // 实现并启动线程
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        InputStream inputStream = null;
                        try {
                            inputStream = new FileInputStream(file);
                            // 跳过已经上传的分片
                            inputStream.skip(startPos);
                            UploadPartRequest uploadPartRequest = new UploadPartRequest();
                            uploadPartRequest.setBucketName(bucketName);
                            uploadPartRequest.setKey(objectName);
                            uploadPartRequest.setUploadId(uploadId);
                            uploadPartRequest.setInputStream(inputStream);
                            // 设置分片大小。除了最后一个分片没有大小限制，其他的分片最小为100 KB。
                            uploadPartRequest.setPartSize(curPartSize);
                            // 设置分片号。每一个上传的分片都有一个分片号，取值范围是1~10000，如果超出这个范围，OSS将返回InvalidArgument的错误码。
                            uploadPartRequest.setPartNumber(partNumber);
                            // 每个分片不需要按顺序上传，甚至可以在不同客户端上传，OSS会按照分片号排序组成完整的文件。
                            UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
                            //每次上传分片之后，OSS的返回结果会包含一个PartETag。PartETag将被保存到PartETags中。
                            synchronized (partETags) {
                                partETags.add(uploadPartResult.getPartETag());
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } finally {
                            if (inputStream != null) {
                                try {
                                    inputStream.close();
                                } catch (IOException e) {
                                    log.error(e.getMessage());
                                }
                            }
                        }
                    }
                });
            }
            // 等待所有的分片完成
            // shutdown方法：通知各个任务（Runnable）的运行结束
            executorService.shutdown();
            while (!executorService.isTerminated()) {
                try {
                    // 指定的时间内所有的任务都结束的时候，返回true，反之返回false，返回false还有执行完的任务
                    executorService.awaitTermination(5, TimeUnit.SECONDS);
                } catch (InterruptedException e) {
                    log.error(e.getMessage());
                }
            }
            // 立即关闭所有执行中的线程
            // executorService.shutdownNow();

            // 验证是否所有的分片都完成
            if (partETags.size() != partCount) {
                throw new IllegalStateException("文件的某些部分上传失败！");
            } else {
                log.info("文件上传成功：" + file.getName());
            }
            // 完成分片上传 进行排序。partETags必须按分片号升序排列
            Collections.sort(partETags, new Comparator<PartETag>() {
                @Override
                public int compare(PartETag o1, PartETag o2) {
                    return o1.getPartNumber() - o2.getPartNumber();
                }
            });
            // 创建CompleteMultipartUploadRequest对象
            // 在执行完成分片上传操作时，需要提供所有有效的partETags。OSS收到提交的partETags后，会逐一验证每个分片的有效性。当所有的数据分片验证通过后，OSS将把这些分片组合成一个完整的文件
            CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(bucketName, objectName, uploadId, partETags);
            // 设置文件访问权限
            // completeMultipartUploadRequest.setObjectACL(CannedAccessControlList.PublicRead);
            // 完成上传
            CompleteMultipartUploadResult completeMultipartUploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest);
            if (completeMultipartUploadResult != null) {
                // 解析结果
                resultArr[0] = completeMultipartUploadResult.getETag();
                resultArr[1] = objectName;
                return resultArr;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }
        return null;
    }

    public String uploadToOSSWithFileName(InputStream inputStream, String fileName, String fileFolder) {
        String fileUrl = null;
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(inputStream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            String fileExtension = fileName.substring(fileName.lastIndexOf("."));
            objectMetadata.setContentType(getContentType(fileExtension));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);

            //上传文件
            PutObjectResult putResult = ossClient.putObject(bucketName, rootFolder+fileFolder+fileName, inputStream, objectMetadata);
            String uploadResult = putResult.getETag();
            if(!StringUtils.isEmpty(uploadResult)){
                fileUrl = ossUrl+rootFolder+fileFolder+fileName;
                logger.info("上传文件的fileUrl={}", fileUrl);
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return fileUrl;
    }
}
